import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Table, Tag, Space, Tooltip, Button, Modal, Form, Select, message, Input } from 'antd';
import { WifiOutlined, VideoCameraAddOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import LiveCameraFeed from './LiveCameraFeed';
import { useWebSocket } from '../../contexts/WebSocketContext';
import type { Device } from '../../contexts/WebSocketContext';
import axios from 'axios';

const { Option } = Select;

const DeviceList: React.FC = () => {
    const { devices, isConnected } = useWebSocket();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
    const [cameraServices, setCameraServices] = useState<string[]>([]);
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        const fetchCameraServices = async () => {
            try {
                const token = localStorage.getItem('adminAuthToken');
                const response = await axios.get('/api/admin/camera_services/', {
                    headers: { Authorization: `Token ${token}` },
                });
                setCameraServices(response.data);
            } catch (error) {
                console.error("获取摄像头服务列表失败:", error);
                message.error("无法加载可用的摄像头列表。");
            }
        };

        fetchCameraServices();
    }, []);

    const showBindModal = (device: Device) => {
        setSelectedDevice(device);
        form.setFieldsValue({ camera_service_name: device.camera_service_name || undefined });
        setIsModalVisible(true);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
        setSelectedDevice(null);
        form.resetFields();
    };

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            if (!selectedDevice) return;

            setLoading(true);
            const token = localStorage.getItem('adminAuthToken');
            await axios.post(
                `/api/admin/devices/${selectedDevice.device_id}/bind_camera/`,
                { camera_service_name: values.camera_service_name },
                { headers: { Authorization: `Token ${token}` } }
            );

            message.success(`成功将摄像头 "${values.camera_service_name}" 绑定到设备 "${selectedDevice.name}"`);
            setIsModalVisible(false);
            // The WebSocket update will refresh the list automatically
        } catch (error) {
            console.error("绑定摄像头失败:", error);
            message.error("绑定失败，请检查控制台输出。");
        } finally {
            setLoading(false);
        }
    };

    const columns: ColumnsType<Device> = [
        {
            title: '设备名称',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => <strong>{text} ({record.device_id})</strong>,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: string) => {
                let color;
                if (status === 'online') {
                    color = 'green';
                } else if (status === 'offline') {
                    color = 'red';
                } else {
                    color = 'orange';
                }
                return <Tag color={color}>{status.toUpperCase()}</Tag>;
            },
        },
        {
            title: '位置',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '关联摄像头',
            dataIndex: 'camera_service_name',
            key: 'camera_service_name',
            render: (name) => name ? <Tag color="blue">{name}</Tag> : '未关联',
        },
        {
            title: 'IP地址',
            dataIndex: 'ip_address',
            key: 'ip_address',
            render: (ip) => ip || 'N/A',
        },
        {
            title: '最后在线',
            dataIndex: 'last_seen',
            key: 'last_seen',
            render: (date) => date ? new Date(date).toLocaleString() : '从未',
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            render: (_, record) => (
                <Tooltip title="绑定摄像头">
                    <Button
                        icon={<VideoCameraAddOutlined />}
                        onClick={() => showBindModal(record)}
                    >
                        绑定
                    </Button>
                </Tooltip>
            ),
        },
    ];

    return (
        <>
            <Card
                title="设备列表与状态"
                extra={
                    <Space>
                        <Tag icon={<WifiOutlined />} color={isConnected ? 'success' : 'error'}>
                            {isConnected ? '实时监控已连接' : '监控服务已断开'}
                        </Tag>
                    </Space>
                }
            >
                <Table
                    columns={columns}
                    dataSource={devices}
                    rowKey="device_id"
                    loading={!isConnected && devices.length === 0}
                    pagination={{ pageSize: 10 }}
                    scroll={{ x: 1200 }}
                />
            </Card>
            <Modal
                title={`绑定摄像头到设备: ${selectedDevice?.name}`}
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                confirmLoading={loading}
                destroyOnClose
            >
                <Form form={form} layout="vertical" name="bind_camera_form">
                    <Form.Item
                        name="camera_service_name"
                        label="摄像头服务名称"
                        rules={[{ required: true, message: '请选择一个摄像头服务!' }]}
                        help="从后端配置的可用服务中选择一个。"
                    >
                        <Select placeholder="请选择一个摄像头">
                            {cameraServices.map(serviceName => (
                                <Option key={serviceName} value={serviceName}>
                                    {serviceName}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};


const DeviceManagementPage: React.FC = () => {
    return (
        <div>
            <Row gutter={[24, 24]}>
                <Col span={24}>
                    <LiveCameraFeed />
                </Col>
                <Col span={24}>
                    <DeviceList />
                </Col>
            </Row>
        </div>
    );
};

export default DeviceManagementPage;
